from net_tools.urlTools import urlTools


def parse(url, params):
    # 总体信息解析
    print("\n开始解析网页=》=》=》")
    print("页面地址：  " + url)
    pageSoup = urlTools.getPageSoup(url, params)
    print("页面标题：  " + pageSoup.title.string)
    pageBox = pageSoup.find_all(class_="wrap")[0]  # 页面主体
    searchBox = pageBox.find_all(class_="search-box", recursive=1)[0]
    searchTitle = pageBox.find_all(id="keyboard")[0]["value"]
    searchNum = searchBox.find_all(class_="result")[0].find("strong").string
    print("搜索标题:   " + searchTitle)
    print("搜索数量:   " + searchNum)

    # 分页解析
    pageSize = 25
    sourceList = []
    pageCount = urlTools.calPageCount(int(searchNum), pageSize)
    if pageCount > 10:
        pageCount = 10
    for pageNum in range(1, pageCount + 1, 1):
        print(f"当前页码：{pageNum}")
        params['page'] = pageNum
        pageSoupPre = urlTools.getPageSoup(url, params)
        pageBoxPre = pageSoupPre.find_all(class_="wrap")[0]  # 页面主体

        page = pageBoxPre.select("dl")
        for item in page:
            link = item.find("h2").find("a")
            sourceTitle = link.get_text()
            sourceUrl = link["href"]
            webTopic = item.find("p").find("span").get_text()

            topic = ""
            if "图" in webTopic or sourceTitle:
                topic = "picture"
            else:
                topic = "video"
            # print("   source标题：  "+sourceTitle)
            # print("   source url：  "+sourceUrl)
            # print("   source topic：  "+topic)
            source = {"sourceTitle": sourceTitle, "sourceUrl": sourceUrl, "topic": topic}
            if not "小说" in webTopic:  # 小说不要
                sourceList.append(source)
    resultJson = {"url": url, "searchTitle": searchTitle, "searchNum": searchNum, "resultSize": len(sourceList),
                  "sourceList": sourceList}
    # print("resultSize",len(sourceList))
    # print("resultJson",resultJson)

    print("解析结束=》=》=》")
    return resultJson


def search(keywork):
    url = 'https://www.a678nh.com/searchs/index.php'
    params = {
        'page': 0,
        'classid': 0,
        'keyboard': keywork,
    }
    return parse(url, params)
# keywork = '妹妹'
# search(keywork)
